package com.sixkey.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sixkey.constant.RedisConstant;
import com.sixkey.entity.Department;
import com.sixkey.entity.Message;
import com.sixkey.entity.User;
import com.sixkey.entity.UserMessage;
import com.sixkey.entity.vo.MessageDataVo;
import com.sixkey.entity.vo.MessageVo;
import com.sixkey.mapper.MessageMapper;
import com.sixkey.rabbitmq.RabbitService;
import com.sixkey.service.IDepartmentService;
import com.sixkey.service.IMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sixkey.service.IUserMessageService;
import com.sixkey.service.IUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2023-10-27
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    private final IUserService userService;

    private final RabbitService rabbitService;

    private final RedisTemplate redisTemplate;

    private final IDepartmentService departmentService;

    private final IUserMessageService userMessageService;


    /**
     * 获取管理员或者主管发布的历史通知
     * @param id
     * @return
     */
    @Override
    public List<Map<String, Object>> getHistoryMessage(int id) {
        //根据用户id获取部门id
        User user = userService.getById(id);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("dept_id",user.getDeptId()).and(item -> item.eq("role","主管"));
        //得到管理员或者主管
        User targetUser = userService.getOne(wrapper);
        //根据管理员或者主管id获取他所发过的通知
        List<Message> messages = this.list(new QueryWrapper<Message>().eq("user_id", targetUser.getId()));
        if(CollectionUtils.isEmpty(messages)){
            return null;
        }
        List<Map<String, Object>> list = new ArrayList<>();
        messages.stream().forEach(item -> {
            LocalDateTime createTime = item.getCreateTime();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分钟");
            //2023年07月22日 17时03分钟
            String currentTime = dateTimeFormatter.format(createTime);
            Map<String,Object> map = new HashMap<>();
            map.put("message",item.getMessage());
            map.put("avatar",targetUser.getAvatar());
            map.put("currentTime",currentTime);
            list.add(map);
        });
        return list;
    }

    /**
     * 获获取自己发布过的通知历史
     * @param id
     * @return
     */
    @Override
    public List<Map<String, Object>> getHistoryMessageByOneself(int id) {
        User user = userService.getById(id);
        List<Message> messages = this.list(new QueryWrapper<Message>().eq("user_id", id));
        if(CollectionUtils.isEmpty(messages)){
            return null;
        }
        List<Map<String, Object>> list = new ArrayList<>();
        messages.stream().forEach(item -> {
            LocalDateTime createTime = item.getCreateTime();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分钟");
            //2023年07月22日 17时03分钟
            String currentTime = dateTimeFormatter.format(createTime);
            Map<String,Object> map = new HashMap<>();
            map.put("message",item.getMessage());
            map.put("avatar",user.getAvatar());
            map.put("currentTime",currentTime);
            list.add(map);
        });
        return list;
    }

    /**
     * 获取当前登录用户是否有需要知道的通知
     * @param id
     * @return
     */
    @Override
    public int getBadge(int id) {
        //根据用户id获取部门id
        User user = userService.getById(id);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("dept_id",user.getDeptId()).and(item -> item.eq("role","主管"));
        //得到管理员或者主管
        User targetUser = userService.getOne(wrapper);
        //根据管理员或者主管id获取他的所有发送消息
        List<Message> messages = this.list(new QueryWrapper<Message>().eq("user_id", targetUser.getId()));
        if(CollectionUtils.isEmpty(messages)){
            return 0;
        }
        //过滤出用户未读的消息
        //去记录表查询此消息是否已被读过
        List<Integer> msgIds = messages.stream().map(Message::getId).collect(Collectors.toList());
        int total = 0;
        for (int i = 0; i < msgIds.size(); i++) {
            UserMessage userMessage = userMessageService.getOne(new QueryWrapper<UserMessage>().eq("message_id", msgIds.get(i)).and(item -> item.eq("user_id", id)));
            if(null == userMessage){
                total++;
            }
        }
        return total;
    }

    @Override
    public void saveMessage(MessageVo messageVo) {
        System.out.println(messageVo);
        //将消息存入到redis中作缓存
        redisTemplate.opsForValue().set(RedisConstant.MESSAGE + messageVo.getId(),messageVo);
        Message message = new Message();
        message.setMessage(messageVo.getMessage());
        message.setUserId(messageVo.getId());
        this.save(message);
    }

    @Override
    public Map<String, Object> getMessage(int id) {
        MessageVo messageVo = (MessageVo) redisTemplate.opsForValue().get(RedisConstant.MESSAGE + id);
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分钟");
        //2023年07月22日 17时03分钟
        String currentTime = dateTimeFormatter.format(dateTime);
        Map<String,Object> map = new HashMap<>();
        map.put("message",messageVo.getMessage());
        map.put("avatar",messageVo.getAvatar());
        map.put("currentTime",currentTime);
        //将redis中的缓存数据删除
        redisTemplate.delete(RedisConstant.MESSAGE + id);
        return map;
    }

    /**
     * 获取新通知
     * @param id
     * @return
     */
    @Override
    public List<Map<String, Object>> getNewMessage(int id) {
        //根据用户id获取部门id
        User user = userService.getById(id);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("dept_id",user.getDeptId()).and(item -> item.eq("role","主管"));
        //得到管理员或者主管
        User targetUser = userService.getOne(wrapper);
        //根据管理员或者主管id获取他所发过的通知
        List<Message> messages = this.list(new QueryWrapper<Message>().eq("user_id", targetUser.getId()));
        if(CollectionUtils.isEmpty(messages)){
            return null;
        }
        //将通知状态为0的数据过滤处理返回
        List<Integer> msgIds = messages.stream().map(Message::getId).collect(Collectors.toList());
        List<Map<String, Object>> list = new ArrayList<>();
        msgIds.stream().forEach(item-> {
            UserMessage userMessage = userMessageService.getOne(new QueryWrapper<UserMessage>().eq("message_id", item).and(items -> items.eq("user_id", id)));
            if(userMessage == null){
                //说明这条消息是新的
                Message message = this.getById(item);
                LocalDateTime createTime = message.getCreateTime();
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分钟");
                //2023年07月22日 17时03分钟
                String currentTime = dateTimeFormatter.format(createTime);
                Map<String,Object> map = new HashMap<>();
                map.put("message",message.getMessage());
                map.put("avatar",targetUser.getAvatar());
                map.put("currentTime",currentTime);
                list.add(map);
                //然后将这条消息设置为已读
                UserMessage userMsg = new UserMessage();
                userMsg.setMessageId(item);
                userMsg.setUserId(id);
                userMessageService.save(userMsg);
                log.info("新通知消息插入成功---------------");
            }
        });
        return list;
    }

    /**
     * 通知数据分页查询
     * @param pageNo
     * @param pageSize
     * @param
     * @return
     */
    @Override
    public Map<String,Object> queryList(Integer pageNo, Integer pageSize) {
        Page<Message> pageInfo = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        //添加过滤条件(模糊查询)
        //添加排序条件
        wrapper.orderByDesc(Message::getUpdateTime);
        Page<Message> messagePage = this.page(pageInfo, wrapper);
        //分页的所有数据
        long total = messagePage.getTotal();
        List<Message> records = messagePage.getRecords();
        List<MessageDataVo> list = new ArrayList<>();
        records.stream().forEach(item -> {
            MessageDataVo messageDataVo = new MessageDataVo();
            User user = userService.getById(item.getUserId());
            Department department = departmentService.getById(user.getDeptId());
            messageDataVo.setName(user.getName());
            messageDataVo.setId(item.getId());
            messageDataVo.setPhone(user.getPhone());
            messageDataVo.setAvatar(user.getAvatar());
            messageDataVo.setDeptName(department.getName());
            messageDataVo.setMessage(item.getMessage());
            list.add(messageDataVo);
        });
        Map<String,Object> map = new HashMap<>();
        map.put("data",list);
        map.put("total",total);
        return map;
    }
}
